#!/usr/bin/env python3
"""
HR系统真实应用场景快速测试
验证系统是否能满足HR日常工作的核心需求
"""

import requests
import json
import time
import sys

def test_request(message, test_name, expected_features=None):
    """发送测试请求并验证响应"""
    print(f"\n🧪 {test_name}")
    print(f"💬 查询: {message}")
    
    try:
        response = requests.post(
            "http://localhost:8089/api/chat",
            json={"message": message},
            timeout=15
        )
        
        if response.status_code != 200:
            print(f"❌ HTTP错误: {response.status_code}")
            return False
            
        data = response.json()
        
        if not data.get('success'):
            print(f"❌ API错误: {data.get('error', 'Unknown')}")
            return False
        
        # 分析响应
        message_len = len(data.get('message', ''))
        ui_commands = len(data.get('ui_commands', []))
        candidates = len(data.get('analyzed_candidates', []))
        
        print(f"✅ AI响应: {message_len} 字符")
        print(f"✅ UI指令: {ui_commands} 个")
        print(f"✅ 候选人: {candidates} 个")
        
        if ui_commands > 0:
            commands = [cmd.get('command') for cmd in data.get('ui_commands', [])]
            print(f"✅ 指令类型: {commands}")
        
        # 验证期望特性
        success = True
        if expected_features:
            if expected_features.get('min_response') and message_len < expected_features['min_response']:
                print(f"⚠️  响应过短: {message_len} < {expected_features['min_response']}")
                success = False
            if expected_features.get('need_candidates') and candidates == 0:
                print("⚠️  缺少候选人数据")
                success = False
            if expected_features.get('need_ui_commands') and ui_commands == 0:
                print("⚠️  缺少UI指令")
                success = False
        
        return success
        
    except Exception as e:
        print(f"❌ 请求失败: {e}")
        return False

def main():
    """运行HR核心场景测试"""
    print("🎯 HR系统真实应用场景测试")
    print("=" * 50)
    
    # 等待系统启动
    print("⏳ 等待系统启动...")
    max_retries = 10
    for i in range(max_retries):
        try:
            response = requests.get("http://localhost:8089/api/status", timeout=3)
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 系统已启动: {data['system_status']} | 候选人: {data['candidate_count']}")
                break
        except:
            if i < max_retries - 1:
                print(f"⏳ 等待中...({i+1}/{max_retries})")
                time.sleep(3)
            else:
                print("❌ 系统启动失败")
                return False
    
    # 核心HR场景测试
    tests = [
        {
            "name": "场景1: 候选人筛选",
            "message": "我需要找3个有Python后端经验的工程师，工作经验2年以上",
            "expected": {"need_candidates": True, "need_ui_commands": True, "min_response": 100}
        },
        {
            "name": "场景2: 面试题生成", 
            "message": "给候选人10751444出几道Python面试题，中等难度",
            "expected": {"need_ui_commands": True, "min_response": 150}
        },
        {
            "name": "场景3: 技能分析",
            "message": "分析候选人12415691的技能匹配度，他适合前端开发岗位吗？",
            "expected": {"min_response": 200}
        },
        {
            "name": "场景4: 批量查询",
            "message": "找出所有会Java和Spring的候选人",
            "expected": {"need_candidates": True, "need_ui_commands": True}
        },
        {
            "name": "场景5: 状态管理",
            "message": "将候选人10751444标记为待面试状态",
            "expected": {"min_response": 50}
        },
        {
            "name": "场景6: 对话咨询",
            "message": "我们的招聘流程和标准是什么？",
            "expected": {"min_response": 150}
        },
        {
            "name": "场景7: 数据统计",
            "message": "统计一下候选人的技能分布，哪些技能最受欢迎？",
            "expected": {"min_response": 200}
        },
        {
            "name": "场景8: 复杂筛选",
            "message": "找既有Python又有Go经验，并且有团队管理能力的候选人",
            "expected": {"need_candidates": True, "need_ui_commands": True}
        }
    ]
    
    success_count = 0
    for i, test in enumerate(tests):
        if test_request(test["message"], test["name"], test["expected"]):
            success_count += 1
            print("✅ 测试通过")
        else:
            print("❌ 测试失败")
        
        if i < len(tests) - 1:  # 不是最后一个测试
            time.sleep(2)  # 间隔等待
    
    # 生成测试报告
    print("\n" + "=" * 50)
    print("📊 HR系统测试结果汇总")
    print("=" * 50)
    
    success_rate = success_count / len(tests) * 100
    print(f"通过测试: {success_count}/{len(tests)} ({success_rate:.1f}%)")
    
    if success_rate >= 90:
        print("🎉 优秀! HR系统完全满足实际应用需求")
        status = "EXCELLENT"
    elif success_rate >= 75:
        print("✅ 良好! HR系统基本满足应用需求")
        status = "GOOD"
    elif success_rate >= 60:
        print("⚠️  一般! HR系统部分功能需要改进")
        status = "FAIR"
    else:
        print("❌ 较差! HR系统存在重要缺陷")
        status = "POOR"
    
    # 应用建议
    if success_rate < 100:
        print("\n💡 改进建议:")
        if success_count < len(tests):
            print("- 完善失败的测试场景功能")
            print("- 加强多智能体协同能力")
            print("- 优化用户体验和响应速度")
    
    print(f"\n🏆 最终评级: {status}")
    return success_rate >= 75

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)





